package com.lemon.business.timedtask;

import com.lemon.business.timedtask.job.CacheConfigJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * @Author liuli
 * @Date 2020/10/15 0:18
 */
public class TimedTaskService {
    private static final Logger LOG = LoggerFactory.getLogger(TimedTaskService.class);

    private static Scheduler scheduler;

    public static void start(){
        try {
            JobDetail cacheConfigJob = JobBuilder.newJob(CacheConfigJob.class).withIdentity("cacheConfigJob", "config-job").build();
            SimpleTrigger cacheConfigJobTrigger = TriggerBuilder.newTrigger().forJob(cacheConfigJob).withIdentity("cacheConfigJobTrigger", "config-trigger")
                    .startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatForever().withIntervalInSeconds(60)).build(); // 一分钟一次

            StdSchedulerFactory configFactory = new StdSchedulerFactory();
            Properties prop = new Properties();
            prop.setProperty("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
            prop.setProperty("org.quartz.threadPool.threadCount", "1");
            configFactory.initialize(prop);
            scheduler = configFactory.getScheduler();
            scheduler.scheduleJob(cacheConfigJob, cacheConfigJobTrigger);

            scheduler.start();
            LOG.info("config load service start success.");

        } catch (Exception e){
            LOG.error("config load service start error.", e);
        }
    }

    public static void shutdown(){
        if (scheduler != null){
            try {
                scheduler.shutdown(false);
                LOG.info("config load service shutdown success.");
            }catch (Exception e){
                LOG.error("config load service shutdown error.", e);
            }

        }
    }
}
